<template>
  <div class="app-container">
    <el-row :gutter="24">
      <el-col :span="24" :xs="24">
        <el-card>
          <div class="filter-container">
            <el-input clearable style="margin-left: 20px;width: 140px" class="filter-item" v-model="listQuery.username" placeholder="用户名"></el-input>
            <el-input clearable style="margin-left: 20px;width: 140px" class="filter-item" v-model="listQuery.mobile" placeholder="手机"></el-input>
            <el-select clearable style="margin-left: 20px;width: 140px" class="filter-item" v-model="listQuery.status" placeholder="请选择">
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.name"
                :value="item.value">
              </el-option>
            </el-select>
            <el-button v-if="checkPermission('查询账户')" style="margin-left:40px" class="filter-item" type="primary" icon="el-icon-search" @click="getUserList">
              查询
            </el-button>
            <el-button v-if="checkPermission('添加账户')"  style="margin-left:10px" class="filter-item" type="primary" icon="el-icon-plus" @click="createAccount">
              添加账号
            </el-button>
          </div>
          <div class="app-container">
            <el-table
              :key="tableKey"
              v-loading="listLoading"
              :row-style="{height:40+'px'}"
              :cell-style="{padding:0+'px'}"
              :data="list"
              ref="equipTable"
              border
              fit
              stripe
              highlight-current-row
              style="width: 100%;"
            >
              <el-table-column
                type="index"
                width="50">
              </el-table-column>
              <el-table-column label="公司ID" align="center" width="80">
                <template v-slot="{row}">
                  <span>{{row.id}}</span>
                </template>
              </el-table-column>
              <el-table-column label="用户名" align="center" >
                <template v-slot="{row}">
                  <span>{{row.username }}</span>
                </template>
              </el-table-column>
              <el-table-column label="所属公司" align="center" >
                <template v-slot="{row}">
                  <span>{{row.title}}</span>
                </template>
              </el-table-column>
              <el-table-column label="状态" align="center" >
                <template v-slot="{row}">
                  <el-button size="small" :type=formatStatus(row) circle ></el-button>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="center">
                <template v-slot="{row}">
                  <span>{{formatDate(row.create_time)}}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
                <template v-slot="{row,$index}">
                  <el-button title="阀门开关"  v-if="checkPermission('阀门开关')" :icon="row.setting&&row.setting.is_show_open_valve?'el-icon-video-pause':'el-icon-video-play'" type="primary" circle @click="setShowOpenValue(row,$index)">
                  </el-button>
                  <el-button title="修改账户" v-if="checkPermission('修改账户')" type="primary" icon="el-icon-edit" circle  @click="updateAccount(row)">
                  </el-button>
                  <el-button title="重置密码" v-if="checkPermission('重置密码')" type="primary" icon="el-icon-lock" circle  @click="resetPwd(row)">
                  </el-button>
                  <el-button title="设置抄表字段" v-if="checkPermission('设置抄表字段')" icon="el-icon-tickets" type="primary" circle @click="setMeterColumns(row)">
                  </el-button>
                  <el-button title="配置商户" v-if="checkPermission('配置商户')" icon="el-icon-coin" type="primary" circle @click="saveMchID(row,$index)">
                  </el-button>
                  <el-button title="配置短信签名" v-if="checkPermission('配置短信签名')" icon="el-icon-message" type="primary" circle @click="openSmsSignName(row)">
                  </el-button>
                  <el-button title="删除账户"  v-if="checkPermission('删除账户')" icon="el-icon-delete" type="danger" circle @click="handleDelete(row,$index)">
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total>0" :total="total"  :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getUserList" />
            <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" custom-class="window-small-width">
              <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" >
                <el-form-item label="用户名" prop="username" >
                  <el-input :disabled="dialogStatus == 'update'" v-model="temp.username" />
                </el-form-item>
                <el-form-item v-if="dialogStatus =='create'" label="密码" prop="password" >
                  <el-input v-model="temp.password" maxlength="20" minlength="6" type="password" show-password/>
                </el-form-item>
                <el-form-item label="手机" prop="mobile" >
                  <el-input v-model="temp.mobile" />
                </el-form-item>
                <el-form-item label="昵称" prop="nickname" >
                  <el-input v-model="temp.nickname" />
                </el-form-item>
                <el-form-item label="公司名称" prop="title" >
                  <el-input v-model="temp.title" />
                </el-form-item>
                <el-form-item label="角色" prop="role_id" >
                  <el-select clearable v-model="temp.role_id" placeholder="请选择">
                    <el-option
                      v-for="item in roles"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item  label="状态" prop="status" >
                  <el-switch
                    v-model="temp.status"
                    active-color="#13ce66"
                    active-text="启用"
                    inactive-text="禁用"
                    :active-value="activeValue"
                    :inactive-value="inactiveValue"
                    inactive-color="#ff4949">
                  </el-switch>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                  取消
                </el-button>
                <el-button  type="primary" @click="dialogStatus == 'create' ? handleCreate():handleUpdate()">
                  确认
                </el-button>
              </div>
            </el-dialog>
            <el-dialog title="设置抄表数据字段"  :visible.sync="dialogMeterVisible">
              <el-transfer
                v-model="selectedColumns"
                :titles="['备选字段','已选字段']"
                :props="{
                    key: 'value',
                    label: 'name'
                  }"
                :data="columns">
              </el-transfer>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                  取消
                </el-button>
                <el-button :disabled="this.selectedColumns === 0"  type="primary" @click="handleMeterColumns">
                  确认
                </el-button>
              </div>
            </el-dialog>
            <el-dialog title="设置短信签名" custom-class="window-small-width" :visible.sync="dialogSmsVisible">
              <el-select
                v-model="temp.sms_sign_name" filterable>
                <el-option
                  v-for="item in smsSignList"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                  取消
                </el-button>
                <el-button :disabled="this.selectedColumns === 0"  type="primary" @click="saveSmsSignName">
                  确认
                </el-button>
              </div>
            </el-dialog>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>

import Pagination from '@/components/Pagination'
import path from "path";
import {
  getList,
  deleteUser,
  resetPwd,
  checkUser,
  createUser,
  updateUser,
  meterColumns,
  updateMchID, updateUserSmsSign,
  saveShowOpenValve
} from "@/api/user";
import {getRoles} from "@/api/role";
import {getToken} from "@/utils/auth";
import {checkPermission} from "@/utils/permission";
import {getSmsSignList} from "@/api/sms";

const defaultAccount = {
  username:'',
  password:'',
  nickname:'',
  mobile:'',
  logo:'',
  title:'',
  status:0,
  role_id:0,
}

export default {
  name: 'Account',
  components:{Pagination},
  data() {
    const validateUsername = (rule, value, callback) => {
      if(this.dialogStatus == 'update'){
        return callback()
      }
      if (this.temp.username.length < 5) {
        callback(new Error('用户名长度至少5位'))
      } else {
        checkUser({username:this.temp.username}).then(res => {
          if (res.exists){
            callback(new Error('用户名已存在'))
          } else{
            callback()
          }
        }).catch(err => {
          callback(err)
        })
      }
    }
    return {
      tableKey:0,
      listLoading:true,
      list:[],
      smsSignList:[],
      total:0,
      activeValue: 1,
      inactiveValue: 0,
      listQuery:{
        username:'',
        mobile:'',
        page:1,
        status:-1,
        pageSize:20
      },
      statusList:[{value:-1,name:'请选择状态'},{value:0,name:'禁用'},{value:1,name:'启用'}],
      roles:[],
      temp:'',
      token:'',
      textMap: {
        update: '编辑账号',
        create: '新建账号'
      },
      columns:[
        {name:'正向水量',value:'positive_volume'},
        {name:'结算水量',value:'settlement_daily_volume'},
        {name:'反向水量',value:'reverse_volume'},
        {name:'瞬时流量',value:'flow_rate'},
        {name:'表内时间',value:'volume_time'},
        {name:'电压',value:'voltage_meter'},
        {name:'阀门状态',value:'valve_status'},
        {name:'信号强度',value:'signal_meter'},
        {name:'信噪比',value:'signal_noise'},
        {name:'空管模式',value:'atc_status'},
        {name:'发生复位',value:'reset_status'},
        {name:'反装预警',value:'reverse_warning_status'},
        {name:'线断',value:'under_voltage_status'},
        {name:'电池欠压',value:'meter_battery_status'},
        {name:'参数锁死',value:'factory_lock_status'},
        {name:'电路故障',value:'electrica_fault_status'},
        {name:'传感器预警',value:'sensor_warning_status'},
        {name:'管道漏水',value:'leakage_alarm_status'},
        {name:'水温',value:'temperature'},
        {name:'传感器预警P值',value:'sensor_warning_p_value'},
        {name:'WingID',value:'wing_id'},
        {name:'版本',value:'version'},
        {name:'ICCID',value:'iccid'},
        {name:'剩余水量',value:'left_volume'},
        {name:'剩余金额',value:'left_amount'},
        {name:'周期用水量',value:'period_volume'},
        {name:'当前单价',value:'unit_price'},
        {name:'关阀水量',value:'valve_close_volume'},
        {name:'IMSI',value:'misi'},
        {name:'软件版本',value:'product_version'},
        {name:'预警水量',value:'warning_volume'}
      ],
      selectedColumns:[],
      dialogFormVisible:false,
      dialogMeterVisible:false,
      dialogSmsVisible:false,
      dialogStatus:'create',
      fileTypes:['image/jpeg','image/png'],
      rules: {
        username: [{ validator:validateUsername,required: true, trigger: 'blur' }],
        title: [{ required: true, message: '请输入公司名称', trigger: 'blur'}],
        password: [{ required: true, pattern:/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/,message: '密码至少包含 数字和英文，长度6-20', trigger: 'blur' }],
      },
    }
  },
  created() {
    this.resetTemp()
    this.getUserList()
    this.getRoles()
    this.getSmsSignNames()
    this.token = getToken()
  },
  computed:{
    logos(){
      if(this.temp.logo === ''){
        return []
      }
      return [{name:'',url:path.resolve('/','logo',this.temp.logo)}]
    }
  },
  methods: {
    checkPermission,
    getUserList(){
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getSmsSignNames() {
      getSmsSignList().then(response => {
        this.smsSignList = response.data.list || []
      })
    },
    getRoles(){
      getRoles({}).then(response => {
        this.roles = response.data.list || []
        this.roles.push({id:0,name:'选择角色'})
      })
    },
    createAccount(){
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    setMeterColumns(row){
      this.temp = Object.assign({},row)
      this.dialogMeterVisible = true
      this.selectedColumns = row.meter_columns.length >0 ?JSON.parse(row.meter_columns) : []
    },
    setShowOpenValue(row){
      let mes = ''
      if (row.setting&& row.setting.is_show_open_valve) {
        mes = '确定要关闭阀门开关吗?'
      } else {
        mes = '确定要显示阀门开关吗?'
      }
      const data = {
        id: row.id,
        is_show: row.setting?!row.setting.is_show_open_valve:true
      }
      this.$confirm(mes, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        saveShowOpenValve(data).then(response => {
          if (response.code == 20000) {
            this.$notify({
              title: 'Success',
              message: '设置完成',
              type: 'success',
              duration: 3000
            })
            this.getUserList()
          } else {
            this.$notify({
              title: 'Failed',
              message: '设置失败',
              type: 'error',
              duration: 3000
            })
          }
        })
      }).catch(err =>{})
    },
    handleMeterColumns(){
      meterColumns({id:this.temp.id,columns:JSON.stringify(this.selectedColumns)}).then(res => {
        if (res.code === 20000) {
          this.$notify({
            title: 'Success',
            message: '抄表字段已更新',
            type: 'success',
            duration: 3000
          })
          this.dialogMeterVisible = false
          this.getUserList()
        } else {
          this.$notify({
            title: 'Failed',
            message: res.message,
            type: 'error',
            duration: 3000
          })
        }
      })
    },
    handleCreate(){
      this.$refs['dataForm'].validate((valid) => {
        if(valid){
            createUser(this.temp).then(res => {
              if (res.code == 20000) {
                this.$notify({
                  title: 'Success',
                  message: '创建成功',
                  type: 'success',
                  duration: 3000
                })
                this.dialogFormVisible = false
                this.getUserList()
              } else {
                this.$notify({
                  title: 'Failed',
                  message: '创建失败',
                  type: 'error',
                  duration: 3000
                })
              }
            })
        }
      })
    },
    handleSuccess(res, file){
      if(res.code == 20000){
        this.$message.success('用户创建完成');
        this.dialogStatus = false
      }else{
        this.$message.error(res.message)
      }
    },
    beforeUpload(file){
      if(!file){
        return true
      }
      if (this.fileTypes.indexOf(file.type) == -1){
        this.$message.error('只允许导入png/jpg/jpeg文件');
        return false
      }
      if(file.size / 1024 / 1024 > 0.5 ){
        this.$message.error('文件大小限定0.5M');
        return false
      }
      return true
    },
    updateAccount(row){
      this.temp = Object.assign({},row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    resetPwd(row){
      this.$prompt('请输入新密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/,
        inputErrorMessage: '密码至少包含 数字和英文，长度6-20'
      }).then(({ value }) => {
        resetPwd({id:row.id,new_password: value}).then(res => {
          if(res.code == 20000){
            this.$message.success('密码已重置')
          }
        })
      }).catch(err => {

      })
    },
    saveMchID(row) {
      this.$prompt('请输入微信商户号', '提示', {
        inputValue:row.wechat_mch_id,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        updateMchID({mch_id:value,id:row.id}).then(res => {
          if(res.code === 20000){
            row.wechat_mch_id = value
            this.$message.success('已配置')
          }
        })
     }).catch(err => {})
    },
    openSmsSignName(row) {
      this.temp = Object.assign({},row)
      this.dialogSmsVisible = true
    },
    saveSmsSignName() {
      const data = {
        id: this.temp.id,
        sign_name: this.temp.sms_sign_name
      }
      updateUserSmsSign(data).then(res => {
        if (res.code === 20000) {
          this.$notify({
            title: 'Success',
            message: '设置完成',
            type: 'success',
            duration: 3000
          })
          this.getUserList()
          this.dialogSmsVisible = false
        }
      })
    },
    handleUpdate(){
      this.$refs['dataForm'].validate((valid) => {
        console.log(valid)
        if(valid){
          updateUser(this.temp).then(res => {
            if (res.code == 20000) {
              this.$notify({
                title: 'Success',
                message: '创建成功',
                type: 'success',
                duration: 3000
              })
              this.dialogFormVisible = false
              this.getUserList()
            } else {
              this.$notify({
                title: 'Failed',
                message: '创建失败',
                type: 'error',
                duration: 3000
              })
            }
          })
        }
      })
    },
    handleDelete(row,index){
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser({id:row.id}).then(response => {
          if (response.code == 20000) {
            this.$notify({
              title: 'Success',
              message: '成功删除',
              type: 'success',
              duration: 3000
            })
            this.getUserList()
          } else {
            this.$notify({
              title: 'Failed',
              message: '无法删除',
              type: 'error',
              duration: 3000
            })
          }
        })
      }).catch(err =>{})
    },
    formatStatus(row){
      switch (row.status){
        case 0:
          return 'danger'
        case 1:
          return 'success'
      }
    },
    formatDate(dateStr) {
      const d = new Date(dateStr)
      if(d.getMilliseconds() === 0){
        return '-'
      }
      return d.toLocaleDateString()
    },
    resetQueryParams(){
      this.listQuery = {
        mobile:'',
        username:'',
        page:1,
        pageSize:20
      }
    },
    resetTemp(){
      this.temp = Object.assign({},defaultAccount)
    }
  }
}
</script>
